<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/13
 * Time: 10:19
 */

namespace app\user\home;

use app\common\controller\ApiBase;
use app\common\exception\ApiError;

require_once  "../extend/wxpay/WxPay.Api.php";

/**
 * 用户支付模块
 * Class Pay
 * @package app\user\home
 */
class Pay extends ApiBase
{

    /**
     * 获取预订单
     * @return \think\response\Json
     * @throws ApiError
     * @throws \WxPayException
     */
    public function test()
    {
        // 参数
        $input = $this->getInput();
        $data = $this->wxPreOrder($input["price"],"test_order");
        return $this->apiSuccess('获取成功',$data);
    }

    /**
     * 获取预订单信息
     * @param $price int 总价
     * @param $order_number
     * @return array
     * @throws \WxPayException
     * @throws ApiError
     */
    private function wxPreOrder($price,$order_number,$title="支付标题"){
        $openid  = $this->user['openid'];

        // 拼接预订单参数
        $order_data = new \WxPayUnifiedOrder();
        $order_data->SetOut_trade_no($order_number);
        $order_data->SetTrade_type('JSAPI');
        $order_data->SetTotal_fee($price * 100);
        $order_data->SetBody($title);
        $order_data->SetOpenid($openid);
        $order_data->SetNotify_url(config('pay_back_url'));

        // 向微信发起请求
        $wx_resp = \WxPayApi::unifiedOrder($order_data);

        if($wx_resp['return_code'] != 'SUCCESS' || $wx_resp['result_code'] !='SUCCESS'){
            throw new ApiError('获取预支付订单失败');
        }

        return $this->getSignature($wx_resp['prepay_id']);
    }

    /**
     * 生成签名
     * @param $prepay_id
     * @return array
     */
    private function getSignature($prepay_id){
        $JSAPI = new \WxPayJsApiPay();
        $JSAPI->SetAppid(config('wechat.app_id'));

        $JSAPI->SetTimeStamp((string)time());
        $rand = md5(time() . mt_rand(0, 1000));
        $JSAPI->SetNonceStr($rand);
        $JSAPI->SetPackage('prepay_id=' . $prepay_id);
        $JSAPI->SetSignType('MD5');
        $sign = $JSAPI->MakeSign();
        $sign_result = $JSAPI->GetValues();

        $sign_result['paySign'] = $sign;
        $sign_result['prepay_id'] = $prepay_id;
        $sign_result['appId'] = config('wechat.app_id');

        return $sign_result;
    }
}